<template>
  <div class="app-container">
    <el-form
      :inline="true"
      @submit.native.prevent
    >
      <el-form-item>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="showAdd"
        >{{ $t("add") }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-input v-model="userName" clearable :placeholder="$t('user')+$t('name')" />
      </el-form-item>
      <el-form-item>
        <el-select v-model="companyId" @change="companyChange">
          <el-option
            v-for="item in companyList"
            :key="item.companyId"
            :label="item.companyName"
            :value="item.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-cascader
          v-model="deptIdList"
          filterable
          :options="treeDeptData"
          :props="{value:'id',label:'name',multiple :true,checkStrictly:true}"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search">
          {{ $t("search") }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="userList"
      style="width: 100%"
    >
      <el-table-column
        prop="userId"
        :label="$t('id')"
        sortable
        width="80"

      />
      <el-table-column :label="$t('icon')" width="50" >
        <template slot-scope="scope">
          <el-image
            style="width: 40px;height: 40px;margin-top: 10px"
            :src="scope.row.iconUrl"
            :preview-src-list="[scope.row.iconUrl]"
            fit="fit"
          >
            <div slot="error" class="image-slot">
              <el-image
                style="width: 40px;height: 40px"
                :src="company.iconUrl"
                fit="fit"
              />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('user')+$t('name')"

      >
        <template slot-scope="scope">
          <span @click="nameClick(scope.row)">{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="companyName"
        :label="$t('company')+$t('name')"

      >
        <template slot-scope="scope">
          <span style="margin-left: 13px" @click="showComapny(scope.row)">{{
              formatCompanyName(scope.row.companyId)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="language"
        :label="$t('language')"

        :formatter="fLanguage"
      />
      <el-table-column
        prop="lastLoginDate"
        :label="$t('last') + $t('login') + $t('time')"
        sortable

      >
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span style="margin-left: 13px">{{
            formatDate(scope.row.lastLoginDate)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column

        prop="registerType"
        :label="$t('type')"
        :formatter="formatRegisterType"
        width="80"
      />
      <el-table-column prop="status" :label="$t('status')"  width="70">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status==1?'success':'danger'" @click="status(scope.row)" v-text="scope.row.status == 1 ? $t('enable'):$t('DISABLE')" />
        </template>
      </el-table-column>
      <el-table-column
        width="350"

        :label="$t('function')"

      >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-cpu"
            @click="showDevices(scope.row)"
          >{{ $t('device') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-connection"
            @click="thirdPartyUser(scope.row)"
          >{{ $t('thirdParty') }}
          </el-button>
          <el-button
            style="color: #f56c6c"
            type="text"
            icon="el-icon-key"
            @click="updateUserPassword(scope.row)"
          >{{ $t('reset') + $t('password') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="edit(scope.row)"
          >{{ $t('edit') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-set-up"
            @click="iotGetUser(scope.row)"
          >{{ $t('iot') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right;margin: 15px 0">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :visible.sync="dialogFormVisible"
    >
      <el-form
        label-width="120px"
      >
        <el-form-item :label="$t('user')+$t('name')">
          <el-input v-model="authUser.userName" :disabled="authUser.userId" />
        </el-form-item>
        <el-form-item :label="$t('email')">
          <el-input v-model="authUser.email" />
        </el-form-item>
        <el-form-item :label="$t('phoneNumber')">
          <el-input v-model="authUser.phoneNumber" />
        </el-form-item>
        <el-form-item :label="$t('company')">
          <el-select v-model="companyId">
            <el-option
              v-for="item in companyList"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="!authUser.userId"
          :label="$t('password')"
        >
          <el-input v-model="authUser.password" />
        </el-form-item>
        <el-form-item :label="$t('singleLogin')">
          <el-switch
            v-model="authUser.singleLogin"
            :active-text="$t('open')"
            :inactive-text="$t('close')"
          />
        </el-form-item>
        <el-form-item :label="$t('devModel')">
          <el-switch
            v-model="authUser.devModel"
            :active-text="$t('open')"
            :inactive-text="$t('close')"
          />
        </el-form-item>
        <el-form-item :label="$t('dept')">
          <el-cascader
            v-model="authUser.deptId"
            filterable
            :options="treeDeptData"
            :props="{value:'id',label:'name',checkStrictly:true,emitPath:false}"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="addOrUpdate">{{ $t("confirm") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogChangeNameVisible"
    >
      <el-form
        label-width="120px"
      >
        <el-form-item :label="$t('user')+$t('name')">
          <el-input v-model="authUser.userName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogChangeNameVisible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="updateName">{{ $t("confirm") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('company')"
      :visible.sync="dialogChangeCompanyVisible"
    >
      <el-form>
        <el-form-item :label="$t('company')" label-width="20%">
          <el-select v-model="companyId">
            <el-option
              v-for="item in companyList"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogChangeCompanyVisible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="changeCompany">{{ $t("confirm") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="authUser.userName"
      :visible.sync="dialogDeviceVisible"
      top="15px"
      width="1000px"
    >
      <user-device v-if="dialogDeviceVisible" :user-id="authUser.userId" />
    </el-dialog>

    <el-dialog
      :visible.sync="dialogIotUserVisible"
    >
      <el-form
        label-width="120px"
      >
        <el-form-item :label="$t('role')">
          <el-select v-model="iotUser.roleIdList" multiple>
            <el-option
              v-for="item in companyRoleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('rule')">
          <el-select
            v-model="iotUser.deviceBelongRuleGroupIdList"
            multiple
          >
            <el-option
              v-for="item in deviceBelongRuleGroupList"
              :key="item.ruleGroupId"
              :label="item.name"
              :value="item.ruleGroupId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogIotUserVisible = false">{{
          $t("cancel")
        }}</el-button>
        <el-button type="primary" @click="updateIotUser">{{
          $t("confirm")
        }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { listCompanyRole } from '@/api/iot/iotCompanyRoleApi'
import {
  formatDate,
  successNotice,
  cancelNotice,
  formatRegisterType
} from '@/util/common'
import {
  updateUser,
  registerUser,
  pageGetUser,
  getInfo,
  updateUserPassword,
  updateUserName
} from '@/api/auth/authUserApi'
import { listAllCompany } from '@/api/auth/authCompanyApi'
import { getCompanyId } from '@/util/storage'
import { listDeviceBelongRuleGroup } from '@/api/iot/iotDeviceBelongRuleGroupApi'
import { treeCompanyDept } from '@/api/auth/authCompanyDeptApi'
import {
  getPageSize,
  setPageSize
} from '@/util/storage'
import UserDevice from '@/components/UserDevice'
import { iotGetUser, iotUpdateUser } from '@/api/iot/iotUserApi'
export default {
  name: 'AllUser',
  components: {
    UserDevice
  },
  data() {
    return {
      userList: [],
      dialogFormVisible: false,
      dialogDeviceVisible: false,
      dialogIotUserVisible: false,
      dialogChangeNameVisible: false,
      userName: null,
      authUser: {},
      iotUser: {},
      currentPage: 1,
      total: 0,
      pageSize: getPageSize(),
      deptIdList: [],
      companyList: [],
      company:{},
      companyId: parseInt(getCompanyId()),
      dialogChangeCompanyVisible: false,
      treeDeptData: [],
      companyRoleList: [],
      deviceBelongRuleGroupList: []
    }
  },
  mounted() {
    this.listAllCompany()
  },
  methods: {
    nameClick(item) {
      this.authUser = item
      this.dialogChangeNameVisible = true
    },
    updateName() {
      updateUserName({
        userId: this.authUser.userId,
        userName: this.authUser.userName
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.pageGetUser()
      })
    },
    iotGetUser(item) {
      iotGetUser({
        userId: item.userId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.iotUser = data
          this.dialogIotUserVisible = true
        }
      })
    },
    companyChange() {
      this.companyList.forEach(item=>{
        if(item.companyId === this.companyId){
          this.company =item
        }
      })
      this.listDeviceBelongRuleGroup()
      this.listCompanyRole()
      this.treeCompanyDept()
    },
    treeCompanyDept() {
      treeCompanyDept({ companyId: this.companyId }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.treeDeptData = data
        }
      })
    },
    showDevices(item) {
      this.authUser = item
      this.dialogDeviceVisible = true
    },
    updateIotUser() {
      iotUpdateUser(this.iotUser).then(res => {
        const { code } = res
        if (code === '200') {
          this.dialogIotUserVisible = false
        }
      })
    },
    listDeviceBelongRuleGroup() {
      listDeviceBelongRuleGroup({
        companyId: this.companyId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.deviceBelongRuleGroupList = data
        }
      })
    },
    listCompanyRole() {
      listCompanyRole({
        companyId: this.companyId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.companyRoleList = data
        }
      })
    },
    listAllCompany() {
      listAllCompany().then(res => {
        const { code, data } = res
        if (code === '200') {
          this.companyList = data
          this.companyChange()
          this.pageGetUser()
        }
      })
    },
    formatCompanyName(companyId) {
      for (const company of this.companyList) {
        if (companyId === company.companyId) {
          return company.companyName
        }
      }
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    fLanguage(item) {
      return this.$t(item.language)
    },
    showComapny(item) {
      this.authUser = item
      this.dialogChangeCompanyVisible = true
    },
    changeCompany() {
      /**
       * 获取用户列表用于产品转让
       * @type {{userId}}
       */
      updateUser({
        userId: this.authUser.userId,
        companyId: this.companyId
      }).then(res => {
        if (res.code === '200') {
          successNotice(this)
          this.pageGetUser()
          this.dialogChangeCompanyVisible = false
        }
      })
    },
    thirdPartyUser(item) {
      this.$router.push({
        path: '/user/third-party',
        query: { userId: item.userId, userName: item.userName }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      setPageSize(this.pageSize)
      this.pageGetUser()
    },
    handleCurrentChange(item) {
      this.currentPage = item
      this.pageGetUser()
    },
    search() {
      this.currentPage = 0
      this.pageGetUser()
    },
    formatRegisterType(item) {
      return formatRegisterType(this, item.registerType)
    },
    edit(item) {
      this.authUser = item
      this.listDeviceBelongRuleGroup()
      this.listCompanyRole()
      getInfo({
        userId: item.userId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.model = 'update'
          this.authUser = data
          this.dialogFormVisible = true
        }
      })
    },
    updateUserPassword(item) {
      const that = this
      this.$confirm(
        item.userName + this.$t('reset') + this.$t('password') + ' 123456',
        this.$t('prompt'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      )
        .then(function() {
          updateUserPassword({
            userId: item.userId,
            password: '123456'
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
              that.pageGetUser()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    status(item) {
      const that = this
      this.$confirm('改变该用户状态, 是否继续?', this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          let json
          if (item.status === 1) {
            json = {
              userId: item.userId,
              status: 0
            }
          } else {
            json = {
              userId: item.userId,
              status: 1
            }
          }
          updateUser(json).then(res => {
            const { code } = res
            if (code === '200') {
              that.pageGetUser()
              successNotice(that)
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    pageGetUser() {
      if (this.deptIdList === '') {
        this.deptIdList = null
      }
      pageGetUser({
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        userName: this.userName,
        companyId: this.companyId,
        deptIdList: this.deptIdList
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.total = data.total
          this.userList = data.data
        }
      })
    },
    showAdd() {
      this.authUser = {
        companyId: this.companyId
      }
      this.dialogFormVisible = true
    },
    addOrUpdate() {
      if (this.authUser.userName == null || this.authUser.userName === '') {
        this.$message.error('请填写用户名')
        return
      }

      const json = {
        companyId: this.companyId,
        ...this.authUser
      }

      if (!this.authUser.userId) {
        if (this.authUser.password == null || this.authUser.password === '') {
          this.$message.error('请填写密码')
          return
        }
        json.password = this.authUser.password
        json.registerType = 'admin'
        registerUser(json).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.dialogFormVisible = false
            this.pageGetUser()
          }
        })
      } else {
        json.userId = this.authUser.userId
        updateUser(json).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.dialogFormVisible = false
            this.pageGetUser()
          }
        })
      }
    }
  }
}

</script>
